#!/bin/bash
# 数据库和文件备份脚本

set -e

# 配置
BACKUP_DIR="/opt/backups"
DATE=$(date +%Y%m%d_%H%M%S)
RETENTION_DAYS=7

# 从环境变量读取数据库配置（或直接修改）
DB_NAME="${DB_NAME:-nanchang_tour}"
DB_USER="${DB_USER:-nanchang_user}"
DB_PASSWORD="${DB_PASSWORD:-your_password}"
DB_HOST="${DB_HOST:-localhost}"

# 创建备份目录
mkdir -p $BACKUP_DIR

echo "=========================================="
echo "开始备份 - $DATE"
echo "=========================================="

# 备份数据库
echo "备份数据库..."
mysqldump -h $DB_HOST -u $DB_USER -p"$DB_PASSWORD" \
    --single-transaction \
    --routines \
    --triggers \
    $DB_NAME > $BACKUP_DIR/db_$DATE.sql

# 压缩数据库备份
gzip $BACKUP_DIR/db_$DATE.sql
echo "数据库备份完成: db_$DATE.sql.gz"

# 备份媒体文件
echo "备份媒体文件..."
if [ -d "/opt/nanchang_tour/backend/media" ]; then
    tar -czf $BACKUP_DIR/media_$DATE.tar.gz \
        -C /opt/nanchang_tour/backend media/
    echo "媒体文件备份完成: media_$DATE.tar.gz"
else
    echo "警告: 媒体文件目录不存在"
fi

# 备份静态文件（可选）
echo "备份静态文件..."
if [ -d "/opt/nanchang_tour/backend/staticfiles" ]; then
    tar -czf $BACKUP_DIR/staticfiles_$DATE.tar.gz \
        -C /opt/nanchang_tour/backend staticfiles/
    echo "静态文件备份完成: staticfiles_$DATE.tar.gz"
fi

# 删除旧备份（保留指定天数）
echo "清理旧备份（保留${RETENTION_DAYS}天）..."
find $BACKUP_DIR -name "*.sql.gz" -mtime +$RETENTION_DAYS -delete
find $BACKUP_DIR -name "*.tar.gz" -mtime +$RETENTION_DAYS -delete

echo ""
echo "=========================================="
echo "备份完成！"
echo "备份目录: $BACKUP_DIR"
echo "=========================================="

# 显示备份文件大小
du -h $BACKUP_DIR/*$DATE*

